import { createRouter, createWebHistory } from 'vue-router'
import { useLoginStore } from "../stores/login"
import jsCookie from 'js-cookie'

const LoginView = () => import('../views/Login.vue')
const IndexView = () => import('../views/Index.vue')
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/index'
    },
    {
      path: '/index',
      name: 'IndexView',
      redirect: '/index/home',
      meta: {
        title: "主页"
      },
      component: IndexView,
      children: [
        {
          name: 'redirect',
          path: 'redirect/:backpath(.*)',
          component: () => import('@/views/redirect/index.vue')
        },
        {
          name: 'userinfo',
          path: 'userinfo',
          component: () => import('@/views/admin/UserInfo.vue'),
          meta: {
            title: "ribbon.userinfo"
          },
        },
        {
          name: 'modifypassword',
          path: 'modifypassword',
          component: () => import('@/views/admin/ModifyPassword.vue'),
          meta: {
            title: "ribbon.modifypassword"
          },
        }
      ]

    },
    {
      path: '/login',
      name: 'LoginView',
      component: LoginView
    },
    {
      path: '/404',
      name: '404',
      component: () => import('../views/404.vue')
    },
    {
      path: '/:path(.*)+',
      redirect: '/404'
    }
  ]
})



// 权限路由守卫
// router.beforeEach(async (to, from) => {
//   const loginStore = useLoginStore()
//   //检查用户是否登录
//   if (!loginStore.token && to.name !== "LoginView") {
//     return { name: "LoginView" }
//   }
// })

router.beforeEach((to, from) => {
  const token = jsCookie.get('token')
  //检查用户是否登录
  if (!token && to.name != "LoginView") {     //必须过滤掉登录页面，否则会出现死循环
    // 回到登录页面
    router.replace({path:'/login',query:{back:to.fullPath}})

    return false
  }
  return true
})


export default router
